<?php
                /*
                * Status Codes:
                - 200 = gernally okay
                - 403 = forbidden
                - Response Text:
                - 601: galaxy view inserted
                - 602: problem with inserting galaxy view
                - 611: report inserted
                - 612: at least one report was wrong
                - 621: stats updated
                - 622: stats not updated
                - 623: stats not changed
                - 631: allyhistory updated
                - 632: allyhistory not updated
                - 642: unmatched ogame server
                - 682: not supported in current version
                * @see galaxyplugin.js
                */

ob_start(); // ignore any echos to be sure that header() works

@require "config.php";
@include_once "../languages/english.inc.php"; // avoid problems with unkown constants
@include_once "../debug.php";

//_debug($_POST);
//$fp = fopen("../tests/galaxyplugin.txt","a");
//if (isset($_POST['typ'])) // fwrite($fp,"beginning with: ".$_POST['typ']."...\n");

$mysqlcon = mysql_connect($dbhost,$dbusername,$dbpassword) or die("");
mysql_select_db($dbname) or die("");

if (isset($_POST['user']) && isset($_POST['password']) && !empty($_POST['user']) && !empty($_POST['password'])) {
    // check user data
    $query = "SELECT id, caninsert, allyhistory, ogameserver FROM $utablename WHERE username='".mysql_real_escape_string(stripslashes($_POST['user']))."' AND userpass='".md5(mysql_real_escape_string(stripslashes($_POST['password'])))."' AND status='active'";
    $res = mysql_query($query) or die("");
    // fwrite($fp,"checking rights... found ".mysql_num_rows($res)." entries\n");
    if (mysql_num_rows($res) > 0) {
        $line = mysql_fetch_object($res);
        $userid = $line->id;
        $ogameserver = $line->ogameserver;
        $allow_insert        = $line->caninsert;
        $allowed_allyhistory = $line->allyhistory;

        // fwrite($fp,"who: ".$_POST['who']."   what: ".$_POST['what']." allowed insert: $allow_insert  ...\n");
        if (isset($_POST['typ']) && $_POST['typ']=="stats" && isset($_POST['content']) && !empty($_POST['content'])
        && isset($_POST['who']) && is_numeric($_POST['who']) && ((int)($_POST['who']) == 0 || (int)($_POST['who']) == 1)
        && isset($_POST['what']) && is_numeric($_POST['what']) && ((int)($_POST['what']) == 0 || (int)($_POST['what']) == 1 || (int)($_POST['what']) == 2)
        && $allow_insert == "true" ) {
            // fwrite($fp,"stats...\n");
            // stats
            $statstext = trim($_POST['content']);
	    if(get_magic_quotes_gpc()) {
			$statstext = strip_tags(stripslashes($statstext));
		}       
            $who = (int)$_POST['who'];
            $what = (int)$_POST['what'];
            if ($who == 0) {
                // fwrite($fp,"playerstats...\n");
                // Playerstats
                $newarray = preg_split('/&(ranks|players|pIds|alliances|points)=/',$statstext,-1,PREG_SPLIT_NO_EMPTY);
		if(count($newarray) != 5) {
			ob_end_clean();
                	echo("622 stats not updated");
                	exit();
		}
		$infoarray = array();
		$a1 = explode('|', $newarray[0]);
		$a2 = explode('|', $newarray[1]);
		$a3 = explode('|', $newarray[2]);
		$a4 = explode('|', $newarray[3]);
		$a5 = explode('|', $newarray[4]);
		if(count($a1) <=0 || count($a2) != count($a1) || count($a3) != count($a1) || count($a4) != count($a1) || count($a5) != count($a1)) {
			ob_end_clean();
                	echo("622 stats not updated");
                	exit();
		}

		for($i=0;$i<count($a1);$i++) {
			$infoarray[$i] = array((int)(trim($a1[$i])), trim($a2[$i]), trim($a4[$i]), (int)(trim($a5[$i])), trim($a3[$i]));
			//($rank, $playername, $ally, $points, $ogameid);
		}

		$adddate = date("Y-m-d H:i:s");
		// check whether these data has been upload or not
		$changed = false;
		foreach ($infoarray as $data) {
			$rank = $data[0];
			$playername = mysql_real_escape_string($data[1]);
			$points = $data[3];
			switch ($what) {
				case 0: $query = "select * from $pstablename where userid=$userid and playername='$playername' and rank=$rank and points=$points"; break;
				case 1: $query = "select * from $pstablename where userid=$userid and playername='$playername' and frank=$rank and fpoints=$points"; break;
				case 2: $query = "select * from $pstablename where userid=$userid and playername='$playername' and rrank=$rank and rpoints=$points"; break;
			}
			$res = mysql_query($query);
			if(!$res) {
				ob_end_clean();
	                	echo("622 stats not updated");
	                	exit();
			} else if (!mysql_fetch_row($res)) {
				$changed = true;
				break;
			}
		}
		if (!$changed) {
				ob_end_clean();
	                	echo("623 stats not changed");
	                	exit();
		}

		if ($changed && count($infoarray) > 0)
		foreach ($infoarray as $data) {
			$rank = $data[0];
			$playername = mysql_real_escape_string($data[1]);
			$ally = mysql_real_escape_string($data[2]);
			$points = $data[3];
			$ogame_playerid = (int)($data[4]);
			
			if($what == 0) {
				$query = "select ind from $pptrends where userid=$userid and playername='$playername'";
				$res = mysql_query($query);
				if (!$res) {
					ob_end_clean();
		                	echo("622 stats not updated");
		                	exit();
				} else if ($row = mysql_fetch_object($res)) {
					$oind = $row->ind;
					$nind = ($oind+1==15 ? 1 : $oind+1);
					$query = " UPDATE $pptrends "."SET ogame_playerid=$ogame_playerid, allyname='$ally', rank=$rank, points=$points, ind=$nind, rank_$nind=$rank, points_$nind=$points, update_$nind='$adddate', last_update='$adddate'".
					" where userid=$userid and playername='$playername'";
					if(!mysql_query($query)) {
						ob_end_clean();
			                	echo("622 stats not updated");
			                	exit();
					}
				} else { // insert a new empty record
					$query = "INSERT INTO $pptrends (userid, playername, ogame_playerid, allyname, rank, points, ind, rank_1, points_1, update_1, last_update) ".
					" values($userid, '$playername', $ogame_playerid, '$ally', $rank, $points, 1, $rank, $points, '$adddate', '$adddate')";
					if(!mysql_query($query)) {
						ob_end_clean();
			                	echo("622 stats not updated");
			                	exit();
			                }
				}
			}
			// update $pstablename
			$query = "INSERT IGNORE INTO $pstablename (userid, playername) values($userid, '$playername')";
			if(!mysql_query($query)) {
						ob_end_clean();
			                	echo("622 stats not updated");
			                	exit();
			}
			switch ($what) {			
				case 0: $query = "UPDATE $pstablename set ogame_playerid=$ogame_playerid, points=$points, ally='$ally', rank=$rank, last_update='$adddate' WHERE userid=$userid and playername='$playername'"; break;
				case 1: $query = "UPDATE $pstablename set ogame_playerid=$ogame_playerid, fpoints=$points, ally='$ally', frank=$rank, last_update='$adddate' WHERE userid=$userid and playername='$playername'"; break;
				case 2: $query = "UPDATE $pstablename set ogame_playerid=$ogame_playerid, rpoints=$points, ally='$ally', rrank=$rank, last_update='$adddate' WHERE userid=$userid and playername='$playername'"; break;
			}
			if(!mysql_query($query)) {
				ob_end_clean();
	                	echo("622 stats not updated");
	                	exit();
			}
		}

                // delete all stats from players who had no update since 30 days (update rank to -1)
                $query = "UPDATE $pstablename set rank=-1, points=-1, frank=-1, fpoints=-1, rrank=-1, rpoints=-1 WHERE userid=$userid and last_update < DATE_SUB(CURDATE(),INTERVAL 30 DAY) and rank>0";
                $res = mysql_query($query);

                ob_end_clean();
                echo("621 Stats updated");
                exit();
            } elseif ($who == 1) {
                // fwrite($fp,"fleetstats...\n");
                // Allystats
                $newarray = preg_split('/&(ranks|members|alliances|points)=/',$statstext,-1,PREG_SPLIT_NO_EMPTY);
		if(count($newarray) != 4) {
			ob_end_clean();
                	echo("622 stats not updated");
                	exit();
		}
		$infoarray = array();
		$a1 = explode('|', $newarray[0]);
		$a2 = explode('|', $newarray[1]);
		$a3 = explode('|', $newarray[2]);
		$a4 = explode('|', $newarray[3]);
		if(count($a1) <=0 || count($a2) != count($a1) || count($a3) != count($a1) || count($a4) != count($a1)) {
			ob_end_clean();
                	echo("622 stats not updated");
                	exit();
		}

		for($i=0;$i<count($a1);$i++) {
			$infoarray[$i] = array((int)(trim($a1[$i])), trim($a2[$i]), (int)(trim($a3[$i])), (int)(trim($a4[$i])));
			//($rank, $ally, $member, $points);
		}

		$adddate = date("Y-m-d H:i:s");
		// check whether these data has been upload or not
		$changed = false;
		foreach ($infoarray as $data) {
			$rank = $data[0];
			$allyname = mysql_real_escape_string($data[1]);
			$members = $data[2];
			$points = $data[3];
			switch ($what) {
				case 0: $query = "select * from $astablename where userid=$userid and allyname='$allyname' and rank=$rank and points=$points and members=$members"; break;
				case 1: $query = "select * from $astablename where userid=$userid and allyname='$allyname' and frank=$rank and fpoints=$points and members=$members"; break;
				case 2: $query = "select * from $astablename where userid=$userid and allyname='$allyname' and rrank=$rank and rpoints=$points and members=$members"; break;
			}
			$res = mysql_query($query);
			if(!$res) {
				ob_end_clean();
	                	echo("622 stats not updated");
	                	exit();
			} else if (!mysql_fetch_row($res)) {
				$changed = true;
				break;
			}
		}

		if (!$changed) {
				ob_end_clean();
	                	echo("623 stats not changed");
	                	exit();
		}

		if ($changed && count($infoarray) > 0)
		foreach ($infoarray as $data) {
			$rank = $data[0];
			$allyname = mysql_real_escape_string($data[1]);
			$members = $data[2];
			$points = $data[3];
			
			$query = "INSERT IGNORE INTO $astablename (userid, allyname) values($userid, '$allyname')";
			if(!mysql_query($query)) {
				ob_end_clean();
	                	echo("622 stats not updated");
	                	exit();
			}

			switch ($what) {			
				case 0: $query = "UPDATE $astablename set points=$points, rank=$rank, members=$members, last_update='$adddate' WHERE userid=$userid and allyname='$allyname'"; break;
				case 1: $query = "UPDATE $astablename set fpoints=$points, frank=$rank, members=$members, last_update='$adddate' WHERE userid=$userid and allyname='$allyname'"; break;
				case 2: $query = "UPDATE $astablename set rpoints=$points, rrank=$rank, members=$members, last_update='$adddate' WHERE userid=$userid and allyname='$allyname'"; break;
			}
			if(!mysql_query($query)) {
				ob_end_clean();
	                	echo("622 stats not updated");
	                	exit();
			}
		}

                // delete all stats from players who had no update since 30 days (update rank to -1)
                $query = "UPDATE $astablename set rank=-1, points=-1, frank=-1, fpoints=-1, rrank=-1, rpoints=-1 WHERE userid=$userid and last_update < DATE_SUB(CURDATE(),INTERVAL 30 DAY) and rank>0";
                $res = mysql_query($query);

                ob_end_clean();
                echo("621 Stats updated");
                exit();
            }
        } elseif (isset($_POST['typ']) && $_POST['typ']=="galaxy" && isset($_POST['content']) && !empty($_POST['content'])
        && isset($_POST['galaxy']) && is_numeric($_POST['galaxy'])
        && isset($_POST['system']) && is_numeric($_POST['system'])
        && $allow_insert == "true" ) {
            // fwrite($fp,"galaxyview...\n");
            // fwrite($fp,$_POST['content']);
            // Galaxy view
            $galaxy = (int)$_POST['galaxy'];
            $system = (int)$_POST['system'];
            
            $gv_source = $_POST['content'];

	    if(get_magic_quotes_gpc()) {
			$gv_source = strip_tags(stripslashes($gv_source));
	    }
            $newarray = preg_split("/\n+/",$gv_source, -1);
            $gs = preg_split("/\s+/", trim($newarray[0]), -1);
            $solar = $gs[0];
            if(empty($solar) || ($ogameserver == 'ogame.com.cn' && $solar != "太阳系") || ($ogameserver == 'ogame.tw' && $solar != "太陽系") || ($ogameserver == 'ogame.org' && $solar != "System")) {
	    	         ob_end_clean();
	    	         // fwrite($fp,"gv not updated...\n");
	    	         echo("642 unmatched ogame server");
	    	         exit();
	    }
            $gs = explode(":", $gs[1]);
            $galaxy = (int)$gs[0];
            $system = (int)$gs[1];
	    
	    unset($newarray[0]);
            // fwrite($fp,"array: ".count($newarray)."...\n");
            $inserted = 0;
            
	    $infoarray = array();
	    // Galaxiedaten eintragen
	    $allystats = array();
	    $playerstats = array();

            foreach ($newarray as $entry) {
                $galaxyline = explode("|",$entry);

                $position = (int)trim($galaxyline[0]);
                $planetname = trim($galaxyline[1]);
                $moonsize = (int)trim($galaxyline[2]);
                $moon = ($moonsize > 0) ? "1" : "0";
                $metal_debris = (int)trim($galaxyline[3]);
                $crystal_debris = (int)trim($galaxyline[4]);
                $playername = trim($galaxyline[5]);
                $playerrank = (int)trim($galaxyline[6]);
                $playerstatus = trim($galaxyline[7]);
                 // english+french+italian banned players
                $playerstatus = str_replace("v","u",$playerstatus); // english+spanish+dutch+french+italian vacation mode
                $playerstatus = str_replace("o","u",$playerstatus); // balkan vacation mode
                $playerstatus = str_replace("m","u",$playerstatus); // portugues vacation mode
                $playerstatus = str_replace("k","g",$playerstatus); // balkan banned players
                $playerstatus = str_replace("t","u",$playerstatus); // turkish vacation players
                $playerstatus = str_replace("c","g",$playerstatus); // turkish banned players
                $playerstatus = preg_replace('/[^iIugn]/i','', $playerstatus);
                $allyname = trim($galaxyline[8]);
                $allyrank = (int)trim($galaxyline[9]);
                $allymember = (int)trim($galaxyline[10]);
                $playerid = (int)trim($galaxyline[11]);
                
                $data = array();
                $data['galaxie'] = $galaxy;
                $data['system'] = $system;
                $data['planetnummer'] = $position;
                $data['moon'] = $moon;
                if($moonsize>0) $data['moonsize'] = $moonsize;
                $data['ally'] = $allyname;
                $data['planetname'] = $planetname;
                $data['playername'] = $playername;
                if($metal_debris+$crystal_debris > 0) {
                	$data['metal'] = $metal_debris;
                	$data['crystal'] = $crystal_debris;
                }
                
                $infoarray[] = $data;
                
                if(!empty($allyname)) {
                	if(!isset($allystats[$allyname]))
                		$allystats[$allyname] = array($allyrank, $allymember);
                }
                if(!empty($playername)) {
                	if(!isset($playerstats[$playername]))
                		$playerstats[$playername] = array("ally"=>$allyname, "rank"=>$playerrank, "status"=>$playerstatus, "ogame_playerid"=>$playerid);
                }
                $inserted++;
                if($inserted>=15) break;
            }

		if (count($infoarray) > 1) {
			foreach ($infoarray as $data) {
				if ($data['galaxie'] > 0 && $data['galaxie'] < 51 && $data['system'] > 0 && $data['system'] < 500 && $data['planetnummer'] > 0 && $data['planetnummer'] < 16) {
					$query = "select notices, reports from $dbtablename where userid=$userid and galaxie=".$data['galaxie']." and system=".$data['system']." and planet=".$data['planetnummer'];
					$res = mysql_query($query);
					if (!$res) {
				    	         ob_end_clean();
				    	         echo("602 no update");
				    	         exit();
					}
					$hasRecord = mysql_num_rows($res);
					if($hasRecord) {
						$query = "UPDATE $dbtablename SET " .
						" mond='".$data['moon']."', " . "ally='".$data['ally']."',planetname='".$data['planetname']."',spielername='".$data['playername']."', ".
						"zeit='".time()."' ";
						if (isset($data['moonsize'])) $query .= ", mondgr='".$data['moonsize']."' ";
						if (isset($data['metal'])) $query .= ", metall='".$data['metal']."' ";
						if (isset($data['crystal'])) $query .= ", kristall='".$data['crystal']."' ";
						$query .= "WHERE userid=$userid and galaxie=".$data['galaxie']." and system=".$data['system']." and planet=".$data['planetnummer'];
					} else {
						$query = "INSERT INTO $dbtablename (userid, galaxie, system, planet, coordinates, mond, ally, planetname, spielername, zeit, mondgr, metall, kristall) values($userid, " .
						$data['galaxie'].", ".$data['system'].", ".$data['planetnummer'].", '".$data['galaxie'].":".$data['system'].":".$data['planetnummer']. "', '".
						$data['moon']."', '".$data['ally']."', '".$data['planetname']."', '".$data['playername']."', '".time()."', ";
						if (isset($data['moonsize'])) $query .= "'".$data['moonsize']."', "; else $query .= "0, ";
						if (isset($data['metal'])) $query .= "'".$data['metal']."', "; else $query .= "0, ";
						if (isset($data['crystal'])) $query .= "'".$data['crystal']."')"; else $query .= "0)";
					}
					if (!mysql_query($query)) {
				    	         ob_end_clean();
				    	         echo("602 no update");
				    	         exit();
		    	        	}
				}
			}
		}
		else {
	            ob_end_clean();
	            echo("602 no update");
	            exit();			
		}
		//ally stats
		foreach ($allystats as $allyname => $data) {
			$query = "INSERT IGNORE INTO $astablename (userid, allyname) values($userid, '" . mysql_real_escape_string($allyname) ."')";
			if(!mysql_query($query)) {
			    	         ob_end_clean();
			    	         echo("602 no update");
			    	         exit();
			}
			$query = "UPDATE $astablename set rank=". $data[0] . ", members=". $data[1] .", last_update='". date("Y-m-d H:i:s") ."'" .
				 " WHERE userid=$userid and allyname='" . mysql_real_escape_string($allyname) ."'";
			if(!mysql_query($query)) {
			    	         ob_end_clean();
			    	         echo("602 no update");
			    	         exit();
			}		
		}
		//player stats
		foreach ($playerstats as $playername => $playerarray) {
			$query = "INSERT IGNORE INTO $pstablename (userid, playername) values($userid, '" . mysql_real_escape_string($playername) . "')";
			if(!mysql_query($query)) {
			    	         ob_end_clean();
			    	         echo("602 no update");
			    	         exit();
			}
			
			$query = "UPDATE $pstablename set status='" . $playerarray['status'] . "', ally='" . $playerarray['ally'] . "', rank=" . $playerarray['rank'] .", last_update='". date("Y-m-d H:i:s") ."', ogame_playerid=" . $playerarray['ogame_playerid'] . " WHERE userid=$userid and playername='" . mysql_real_escape_string($playername) ."'";
			if(!mysql_query($query)) {
			    	         ob_end_clean();
			    	         echo("602 no update");
			    	         exit();
			}
		}

            // fwrite($fp,"all entries finished...\n");
                ob_end_clean();
                // fwrite($fp,"gv updated...\n");
                echo("601 Galaxyview updated");
                exit();
        } elseif (isset($_POST['typ']) && $_POST['typ']=="reports" && isset($_POST['content']) && !empty($_POST['content'])
        && $allow_insert == "true" ) {
            ob_end_clean();echo("682 Not supported");exit();
            // fwrite($fp,"reports...\n");
            include_once "spioparser.inc.php";
            $parser = new Probeparser($dbusername,$dbpassword,$dbname,$reporttable,$dbtablename,$dbhost);

            if (strpos($_POST['content'],"Surowce na") === false) {
                $reportstring = str_replace("&nbsp;"," ",utf8_decode(stripslashes($_POST['content'])));
            } else {
                $reportstring = str_replace("&nbsp;"," ",stripslashes($_POST['content']));
            }
            $reportstring = str_replace("</td>"," </td>",$reportstring);
            $reportstring = str_replace("\n","",$reportstring);
            $reportstring = str_replace("</tr>","</tr>\n",$reportstring);
            
            // fwrite($fp,"Reportstring:\n$reportstring\n");
            
            $reportarray = explode("<td colspan=\"3\" class=\"b\">",$reportstring);

            unset($reportarray[0]);

            $reportarray = array_reverse($reportarray);

            // fwrite($fp,"Anzahl im Reportarray: ".count($reportarray)."\n");
            
            $error = false;
            foreach ($reportarray as $row) {
                $row = html_entity_decode($row);
                $row = strip_tags($row);
                $found = true;
                if (strpos($row,"Rohstoffe auf") !== false) {
                    $_SESSION['lang'] = "german";
                } elseif (strpos($row,"Resources on") !== false) {
                    $_SESSION['lang'] = "english";
                } elseif (strpos($row,"Recursos en") !== false) {
                    $_SESSION['lang'] = "spanish";
                } elseif (strpos($row,"Grondstoffen op") !== false) {
                    $_SESSION['lang'] = "dutch";
                } elseif (strpos($row,"Sirovine na") !== false) {
                    $_SESSION['lang'] = "balkan";
                } elseif (strpos($row,"Mati籥s premi籥s sur") !== false) {
                    $_SESSION['lang'] = "french";
                } elseif (strpos($row,"Recursos em") !== false) {
                    $_SESSION['lang'] = "portugues";
                } elseif (strpos($row,"Surowce na") !== false) {
                    $_SESSION['lang'] = "polish";
                }  elseif (strpos($row,"Risorse su") !== false) {
                    $_SESSION['lang'] = "italian";
                }  elseif (strpos($row,"itibariyle mevcut olan hammadde") !== false) {
                    $_SESSION['lang'] = "turkish";
                }  elseif (strpos($row,"R?offer") !== false) {
                    $_SESSION['lang'] = "danish";
                } else {
                    $found = false;
                }
                
                // fwrite($fp, "Found: $found\n");
                if ($found) {

                    $tmp = $parser->parseEntry($row,false); // no flush!
                    if (!$tmp) $error = true;
                }
            }

            if ($error) {
            	// fwrite($fp,"Fehler aufgetreten: ".$tmp->error."\n");
                ob_end_clean();
                echo("612 Report error");
                exit();
            }
			// fwrite($fp,"okay\n");
            ob_end_clean();
            echo("611 Reports inserted");
            exit();
        } elseif (isset($_POST['typ']) && $_POST['typ']=="allyhistory" && isset($_POST['content']) && !empty($_POST['content'])
        && $allowed_allyhistory == "true" ) {
        	ob_end_clean();echo("682 Not supported");exit();
        	
            // fwrite($fp,"allyhistory...\n");
            // Allyhistory
            include_once "allyparser.inc.php";

            $allyparser = new Ally($dbusername,$dbpassword,$dbname,$allyhistory,$utablename,$dbhost);
            $return = $allyparser->set_current_stats(utf8_decode(stripslashes($_POST['content'])));
            ob_end_clean();
            if (!$return) echo("632 Allyhistory not inserted");
            else echo("631 Allyhistory inserted");

        } else {
            // fwrite($fp,"nothing found...\n");
            ob_end_clean();
            header("HTTP/1.0 403 Forbidden");
            exit();
        }
    } else {
        // fwrite($fp,"permission denied...\n");
        ob_end_clean();
        header("HTTP/1.0 403 Forbidden");
        exit();
    }
} else {
    // fwrite($fp,"username not set...\n");
}
//fclose($fp);

?>
